<template>
  <Dialog v-model="dialogVisible" :title="title" :scroll="true">
    <el-table :data="list" v-loading="formLoading">
      <el-table-column label="等级名称" align="left" prop="agentLevelName" />
      <el-table-column label="权重" align="center" prop="agentLevel" />
      <el-table-column label="奖励金额" align="center">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.reward"
            :min="0"
            :precision="2"
            :controls="false"
            class="!w-100%"
            placeholder="奖励金额"
          >
            <template #suffix>元</template>
          </el-input-number>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as LevelApi from '@/api/mall/trade/agent/level'
import { fenToYuan, yuanToFen } from '@/utils'
import { deepClone } from '@/utils/common'

/** 修改上级代理商表单 */
defineOptions({ name: 'UpdateBindUserForm' })
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const list = ref([]) // 列表的数据
const title = ref('')

const dialogVisible = ref(false) // 弹窗的是否展示
// const objectToArray = (obj) => {
//   if (!obj) {
//     return []
//   } else {
//     return Object.keys(obj).map(function (key) {
//       return { level: key, reward: obj[key] }
//     })
//   }
// }
// const arrayToObject = (arr) => {
//   return arr.reduce(function (obj, item) {
//     obj[item.level] = item.reward
//     return obj
//   }, {})
// }

const level = ref()
/** 打开弹窗 */
const open = async (levelInfo, levelList) => {
  // 清空等级设置额

  // 反显上级代理商
  title.value = '设置' + levelInfo.agentLevelName + '推荐奖励'
  level.value = await LevelApi.getLevel(levelInfo.agentLevelId)
  list.value = deepClone(levelList)
  let arr = level.value.recommendReward
  arr.forEach((element: any) => {
    list.value.forEach((ele: any) => {
      if (ele.agentLevel == element.level) {
        ele.reward = fenToYuan(element.reward)
      }
    })
  })
  console.log(list)
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const message = useMessage() // 消息弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
/** 修改上级代理商 */
const submitForm = async () => {
  // 发送操作成功的事件
  let recommendReward = list.value
  const data = { agentLevelId: level.value.agentLevelId } as unknown as LevelApi.LevelVO

  data.recommendReward = recommendReward.map((ele: any) => {
    return {
      reward: yuanToFen(ele.reward),
      level: ele.agentLevel,
      levelName: ele.agentLevelName
    }
  })
  await LevelApi.updateLevel(data)
  message.success('设置成功')
  emit('success')
  dialogVisible.value = false
}
</script>
